package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"server/internal/model"
	"server/pkg/app"
)

func CreateRestful(c *gin.Context) {
	userinfo := GetUser(c)
	_ = c.Request.ParseForm()
	restful := &model.Restful{}
	_ = c.ShouldBind(restful)
	restful.OwnerID = userinfo.ID
	if len(restful.Name) == 0 {
		c.String(http.StatusOK, "接口名为空")
		return
	}

	if restful.FatherID == 0 {
		c.String(http.StatusOK, "未指定目录")
		return
	}
	restful.RestfulMeauID = restful.FatherID
	go CreateLog(c, "API接口", "创建接口"+restful.Name)

	restful.OwnerID = userinfo.ID
	err := restful.Create()
	if err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": restful,
	})
}

func DeleteRestful(c *gin.Context) {
	restful := &model.Restful{}
	restful.Name = c.Param("name")
	if err := restful.Delete(); err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "API接口删除成功")
}

func UpdateRestful(c *gin.Context) {
	restful := &model.Restful{}
	_ = c.ShouldBind(restful)
	if err := restful.Update(); err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "API接口修改成功")
}

func QueryRestful(c *gin.Context) {
	restful := &model.Restful{}
	restful.Name = c.Param("name")
	if err := restful.Delete(); err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "API接口删除成功")
}

func ListRestful(c *gin.Context) {
	var list []model.Restful
	restful := &model.Restful{}
	Search(c, restful, list)
}

func QueryRestfulInfo(c *gin.Context) {
	restful := &model.Restful{}
	QueryByName(restful, c)
}

func RunApi(c *gin.Context) {
	_ = c.Request.ParseForm()
	api := &app.Api{}
	_ = c.ShouldBind(api)

	str, err := api.Run()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10020,
			"err":  err.Error(),
		})
		return
	}
	var jsonData = make(map[string]interface{})
	err = json.Unmarshal([]byte(str), &jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":     http.StatusOK,
			"response": str,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":     http.StatusOK,
		"response": jsonData,
	})
}
